package com.calligraphy.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.calligraphy.bases.utils.KeyUtil;
import com.calligraphy.user.model.Attachment;
import com.calligraphy.user.repository.AttachmentRepository;
import com.calligraphy.user.service.AttachmentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @Author hy
 * @Date 2018/12/27 11:49
 **/
@Service
@Slf4j
public class AttachmentServiceImpl implements AttachmentService {

    @Value("${file.upload.path}")
    public String fileUploadPath;

    @Autowired
    private AttachmentRepository repository;

    @Override
    public String save(@RequestParam(value = "file") MultipartFile file) {
        if (!file.isEmpty()){

            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = format.format(DateUtil.date()) + RandomUtil.randomInt(1000);
            // 文件后缀
            String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String path = fileUploadPath + fileName + "." + fileSuffix;
            File p = new File(path);
            if(!p.getParentFile().exists()){
                p.getParentFile().mkdir();
            }
            try {
                file.transferTo(p);
                return path;
            } catch (IOException e) {
                e.printStackTrace();
            }
            Attachment attachment = new Attachment();
            attachment.setId(KeyUtil.genUniqueKey());
            attachment.setPictureName(fileName);
            attachment.setPicturePath(path);
            attachment.setPictureType(file.getContentType());
            repository.save(attachment);

            return path;
        }
         return "上传图片失败";

    }

}
